// ----------------------------- 获取分类，渲染 ------------------------------------
function renderCategory() {
    axios.get(`/my/category/list`).then(res => {
      console.log(res);
      let { status, data } = res.data;
      if (status === 0) {
        let arr = [];
        data.forEach(item => {
          arr.push(`
          <tr>
              <td>${item.name}</td>
              <td>${item.alias}</td>
              <td>
                <button data-id="${item.id}" data-name="${item.name}" data-alias="${item.alias}" type="button" class="layui-btn layui-btn-xs">编辑</button>
                <button data-id="${item.id}" type="button" class="del layui-btn layui-btn-xs layui-btn-danger">删除</button>
              </td>
            </tr>
          `);
        });
        $('tbody').html(arr.join(''));
      }
    });
  }
  
  renderCategory();
// ----------------------------- 删除分类 ------------------------------------
  $('tbody').on('click', '.del', function () {
    let id = $(this).data('id');
    layer.confirm('你确定要删除吗？', function (index) {
      axios.get(`/my/category/delete?id=${id}`).then(res => {
        let { status, message } = res.data;
        if (status === 0) {
          layer.msg(message);
          renderCategory();
        }
      });
      layer.close(index);
    });
  })
  
  // ---------------------------------- 编辑类别 -------------------------------
  let editIndex;
  // 1. 点击 编辑 按钮，出现弹层
  $('tbody').on('click', 'button:contains("编辑")', function () {
    let shuju = $(this).data();
    // console.log(shuju); 
    editIndex = layer.open({
      type: 1,
      title: '在线调试',
      content: $('#tpl-edit').html(),
      area: ['500px', '250px'],
      success: function () {
        let form = layui.form; 
        form.val('abc', shuju); 
      }
    });
  })
  
  
  // 3. 表单提交，完成更新
  $('body').on('submit', '#edit-form', function (e) {
    e.preventDefault();
    let data = $(this).serialize(); 
    // console.log(data);
    axios.post(`/my/category/update`, data).then(res => {
      let { status, message } = res.data;
      if (status === 0) {
        layer.msg(message);
        renderCategory();
        layer.close(editIndex);
      }
    });
  });

// 添加类别
let addIndex;
$('button:contains("添加类别")').on('click',function () {
  addIndex = layer.open({
    type: 1,
    title: '添加类别',
    content: $('#tpl-add').html(),
    area: ['500px', '250px']
  });
})

$('body').on('submit', '#add-form', function (e) {
  e.preventDefault();
  let data = $(this).serialize(); 
  axios.post(`/my/category/add`, data).then(res => {
    let {status, message} = res.data
    if (status === 0) {
      layer.msg(message)
      renderCategory()
      layer.close(addIndex)
    }
  })
})

